package com.atguigu.lease.web.app.sms;



import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.HttpUtils;
import lombok.SneakyThrows;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableConfigurationProperties(SMSProperties.class)
public class SmsConfiguration {


    @Autowired
    private SMSProperties smsProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${sms.templateId}")
    private String templateId;

    @Value("${sms.signId}")
    private String signId;

    @SneakyThrows
    public void generateAndSendCode(String mobile){
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
        String key = RedisConstant.APP_LOGIN_PREFIX + mobile;
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new Exception(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN.getMessage());
            }
        }

        String param = "**code**:" + code + ",**minute**:5";
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = smsProperties.getAppCode();
        Map<String, String> headers = new HashMap<String, String>();

        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile);
        querys.put("param", param);
        querys.put("smsSignId", signId);
        querys.put("templateId", templateId);
        Map<String, String> bodys = new HashMap<String, String>();

        try {
             HttpUtils.doPost(host, path, method, headers, querys, bodys);
             redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
